package vn.hanelsoft.openwifi.common;

import java.util.ArrayList;
import java.util.List;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.model.object.ObjectFacebook;
import vn.hanelsoft.openwifi.model.object.ObjectWifi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;

import com.google.gson.Gson;

public class UtilsCommon {

	// Check connect wifi
	public static boolean IsWiFiConnected(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getApplicationContext().getSystemService(
						Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI")
							&& info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// check wifi ssid pass
	public static String checkExistWifiOnServer(Context mContext,
			String strBSSID, ArrayList<ObjectWifi> listObjectWifi) {
		for (int i = 0; i < listObjectWifi.size(); i++) {
			try {
				if (listObjectWifi.get(i).getWifiBSSID().equals(strBSSID)) {
					return listObjectWifi.get(i).getWifiPassword();
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return "LuongVD_Failt";
	}

	// connect wifi
	public static void connectWifi(Context mContext, String strSSID,
			String strPassword) {
		WifiConfiguration wifiConfig = new WifiConfiguration();
		wifiConfig.SSID = String.format("\"%s\"", strSSID);
		wifiConfig.preSharedKey = String.format("\"%s\"", strPassword);
		//
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		// remember id
		int netId = wifiManager.addNetwork(wifiConfig);
		wifiManager.disconnect();
		wifiManager.removeNetwork(wifiConfig.networkId);
		wifiManager.enableNetwork(netId, true);
		wifiManager.reconnect();
	}

	// disconnect Wifi and forgot pass
	public static void disConnectWifi(Context mContext) {
		try {
			WifiManager wifiManager = (WifiManager) mContext
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = wifiManager.getConnectionInfo();
			
//			if(UtilsCommon.getStringSetting(mContext, ConstCommon.KEY_WIFI_STORE).equals(wifiInfo.getBSSID()))
//			{
				wifiManager.disconnect();
				wifiManager.removeNetwork(wifiInfo.getNetworkId());
//			}
			UtilsCommon.setStringSetting(mContext, ConstCommon.KEY_WIFI_STORE, "");
			wifiInfo = null;
			wifiManager = null;
			((Activity)mContext).finish();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static ArrayList<ObjectWifi> getListWifiObject(Context mContext,
			ArrayList<ObjectWifi> listWifiOnServer) {
		ArrayList<ObjectWifi> listWifi = new ArrayList<ObjectWifi>();
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		try {
			if (wifiManager.isWifiEnabled() == false) {
				wifiManager.setWifiEnabled(true);
			}
			List<ScanResult> wifiList = wifiManager.getScanResults();
			for (int i = 0; i < wifiList.size(); i++) {

				ScanResult mScanResult = wifiList.get(i);
				String strTypeWifi = mScanResult.capabilities;
				String strBSSID = mScanResult.BSSID;
				String strSSID = mScanResult.SSID;
				String strPassWifi = UtilsCommon.checkExistWifiOnServer(
						mContext, strBSSID, listWifiOnServer);
				if (strPassWifi.equals("LuongVD_Failt") == false) {
					ObjectWifi mObjectWifi = new ObjectWifi();
					mObjectWifi.setWifiBSSID(strBSSID);
					mObjectWifi.setWifiSSID(strSSID);
					mObjectWifi.setWifiPassword(strPassWifi);
					mObjectWifi.setStatusConnect(mContext
							.getString(R.string.not_connect));
					mObjectWifi.setTypeWifi(strTypeWifi);
					listWifi.add(mObjectWifi);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listWifi;
	}

	public static ArrayList<ObjectWifi> getAllListWifiObject(Context mContext) {
		ArrayList<ObjectWifi> listWifi = new ArrayList<ObjectWifi>();
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		try {
			if (wifiManager.isWifiEnabled() == false) {
				wifiManager.setWifiEnabled(true);
			}
			List<ScanResult> wifiList = wifiManager.getScanResults();
			for (int i = 0; i < wifiList.size(); i++) {

				ScanResult mScanResult = wifiList.get(i);
				String strTypeWifi = mScanResult.capabilities;
				String strBSSID = mScanResult.BSSID;
				String strSSID = mScanResult.SSID;
				ObjectWifi mObjectWifi = new ObjectWifi();
				mObjectWifi.setWifiBSSID(strBSSID);
				mObjectWifi.setWifiSSID(strSSID);
				mObjectWifi.setTypeWifi(strTypeWifi);
				listWifi.add(mObjectWifi);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listWifi;
	}

	public static ArrayList<ObjectWifi> getListWifiSave(Context mContext,
			ArrayList<ObjectWifi> listWifiSave) {
		ArrayList<ObjectWifi> listWifi = new ArrayList<ObjectWifi>();
		ArrayList<ObjectWifi> listWifiCurrent = new ArrayList<ObjectWifi>();
		WifiManager wifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		try {
			if (wifiManager.isWifiEnabled() == false) {
				wifiManager.setWifiEnabled(true);
			}
			List<ScanResult> wifiList = wifiManager.getScanResults();
			for (int i = 0; i < wifiList.size(); i++) {

				ScanResult mScanResult = wifiList.get(i);
				String strTypeWifi = mScanResult.capabilities;
				String strBSSID = mScanResult.BSSID;
				String strSSID = mScanResult.SSID;
				ObjectWifi mObjectWifi = new ObjectWifi();
				mObjectWifi.setWifiBSSID(strBSSID);
				mObjectWifi.setWifiSSID(strSSID);
				mObjectWifi.setTypeWifi(strTypeWifi);
				mObjectWifi.setWifiAvailable(0);
				listWifi.add(mObjectWifi);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		for (int j = 0; j < listWifiSave.size(); j++) {
			ObjectWifi mObjectWifiSave = listWifiSave.get(j);
			for (int k = 0; k < listWifi.size(); k++) {
				if(listWifi.get(k).getWifiBSSID().equals(mObjectWifiSave.getWifiBSSID()))
				{
					mObjectWifiSave.setWifiAvailable(1);
					break;
				}
			}
			listWifiCurrent.add(mObjectWifiSave);
		}
		
		return listWifiCurrent;
	}
	
	public static String getStringSetting(Context mContext, String key) {
		SharedPreferences pref = mContext.getSharedPreferences(
				ConstCommon.KEY_SHARE, Activity.MODE_PRIVATE);
		return pref.getString(key, "");
	}

	public static void setStringSetting(Context mContext, String key,
			String value) {
		SharedPreferences pref = mContext.getSharedPreferences(
				ConstCommon.KEY_SHARE, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		editor.putString(key, value);
		editor.commit();
	}

	public static String getStringTypeWifi(String strInputTypeWifi) {
		String strOutput = "WPA";
		String s = strInputTypeWifi.substring(
				strInputTypeWifi.indexOf("[") + 1,
				strInputTypeWifi.indexOf("]"));

		strOutput = s.split("-")[0];
		return strOutput;
	}

	public static String formartUrl(String url){
		if(url.length()>7){
			if(url.substring(0, 7).equals("http://")){
				return url;
			}else if(url.length()>8){
				if(url.substring(0, 8).equals("https://")){
					return url;
				}
			}
		}
		return "http://"+url;
	}
	
	public static String convertObjectToString(ObjectFacebook mObjectFacebook)
	{
		Gson gson = new Gson();
	    String json = gson.toJson(mObjectFacebook);
	    return json;
	}
	
	public static ObjectFacebook convertStringToObject(String str)
	{
		Gson gson = new Gson();
	    ObjectFacebook mObjectFacebook = gson.fromJson(str, ObjectFacebook.class);
	    return mObjectFacebook;
	}
	
	public final static boolean isValidEmail(CharSequence target) {
	    if (target == null) 
	        return false;
	    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
	}
	
	public static void killApp(Context mContext)
	{
		disConnectWifi(mContext);
//		ActivityManager  manager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
//		List<ActivityManager.RunningAppProcessInfo> listOfProcesses = manager.getRunningAppProcesses();
//		for (ActivityManager.RunningAppProcessInfo process : listOfProcesses)
//		{
////		    if (pids.contains(process.pid))
////		    {
//		        Log.d("Luong", "========================== PID: "+process.pid);
//		        Log.d("Luong", "========================== uid: "+process.uid);
//		        Log.d("Luong", "========================== processName: "+process.processName);
//		        manager.restartPackage(process.processName);
//		        
////		        System.exit(0);
//		        android.os.Process.killProcess(process.pid);
////		        android.os.Process.killProcess(android.os.Process.myPid());
////		    }
//		}
	}

	@SuppressWarnings("deprecation")
	public static void turnGPSOn(Context context)
	{
		LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
		boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
	     // only for gingerbread and newer versions
			try{
				Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
			     intent.putExtra("enabled", true);
			     context.sendBroadcast(intent);

			    String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
			    if(!provider.contains("gps")){ //if gps is disabled
			        final Intent poke = new Intent();
			        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
			        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			        poke.setData(Uri.parse("3")); 
			        context.sendBroadcast(poke);
			    }
			}catch(Exception ex){
				AlertDialog.Builder alert =  new Builder(context);
				alert.setMessage("Please turn on GPS!");
				alert.show();
			}
		}
		if(!statusOfGPS){
			AlertDialog.Builder alert =  new Builder(context);
			alert.setMessage("Please turn on GPS!");
			alert.show();
		}
		
	}
	// automatic turn off the gps
	@SuppressWarnings("deprecation")
	public static void turnGPSOff(Context context)
	{
		LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
		boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
		     // only for gingerbread and newer versions
			try{
			    String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
			    if(provider.contains("gps")){ //if gps is enabled
			        final Intent poke = new Intent();
			        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
			        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
			        poke.setData(Uri.parse("3")); 
			        context.sendBroadcast(poke);
			    }
			}catch(Exception ex){
				AlertDialog.Builder alert =  new Builder(context);
				alert.setMessage("Please turn off GPS!");
				alert.show();
			}
		}
		if(!statusOfGPS){
			AlertDialog.Builder alert =  new Builder(context);
			alert.setMessage("Please turn off GPS!");
			alert.show();
		}
	}
	
	public static Typeface getFontCustom(Context mContext)
	{
		Typeface typeface = Typeface.createFromAsset(mContext.getAssets(), "fonts/tt0140m.ttf");
		return typeface;
	}
}
